package com.anjoyo.xgh.musicshare.activity;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.anjoyo.xgh.musicshare.R;
import com.anjoyo.xgh.musicshare.adapter.FavSongAdapter;
import com.anjoyo.xgh.musicshare.api.CollectApi;
import com.anjoyo.xgh.musicshare.application.SongApplication;
import com.anjoyo.xgh.musicshare.db.MusicDBhelper;
import com.anjoyo.xgh.musicshare.entry.Song;
import com.anjoyo.xgh.musicshare.service.Task;
import com.anjoyo.xgh.musicshare.util.Constant;
import com.anjoyo.xgh.musicshare.util.MusicSpf;
import com.anjoyo.xgh.musicshare.util.Constant.PLAYLIST;
import com.anjoyo.xgh.musicshare.util.StringUtil;

public class FavAct extends Activity {
	ArrayList<Song> songs;
	ListView listView;
	int currentpos = -1;
	FavSongAdapter adapter;
	Context con;
	TextView textView;
	CheckBox checkBox;
	MusicDBhelper dBhelper;
	MyFavSongReceiver receiver;

	class MyFavSongReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Constant.ACTION_FAVDOWN_START)) {
				int musicid = intent.getIntExtra("musicid", -1);
				adapter.startprogress(getpos(musicid));
			} else if (action.equals(Constant.ACTION_FAVDOWN_END)) {
				int musicid = intent.getIntExtra("musicid", -1);
				adapter.closeprogress(getpos(musicid));
			}
		}
	}

	public int getpos(int musicid) {
		for (int i = 0; i < songs.size(); i++) {
			if (songs.get(i).getMusicid() == musicid) {
				return i;
			}
		}
		return -1;
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			songs = SongApplication.getInstance().LoadFavSongs();
			 SongApplication.getInstance().ishaveFavFile();
			adapter = new FavSongAdapter(con, songs);
			listView.setAdapter(adapter);
			if (MusicSpf.getisoffline(con)) {
				downFavSong(songs);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fav_layout);
		con = this;
		dBhelper = new MusicDBhelper(con);
		songs = SongApplication.getInstance().LoadFavSongs();
//		songs = SongApplication.getInstance().LoadFavSongs();
		SongApplication.getInstance().changNowPlayList(PLAYLIST.FAV_MUSIC_LIST);
		// 注册广播
		IntentFilter inf = new IntentFilter();
		inf.addAction(Constant.ACTION_FAVDOWN_START);
		inf.addAction(Constant.ACTION_FAVDOWN_END);
		receiver = new MyFavSongReceiver();
		this.registerReceiver(receiver, inf);
		findViewById(R.id.iv_music).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(con, PlayAct.class);
				startActivity(intent);
			}
		});
		// getlist();
		listinit();
		findViewById(R.id.iv_back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		checkBox = (CheckBox) findViewById(R.id.cb_isoffline);
		checkBox.setChecked(MusicSpf.getisoffline(con));
		if (MusicSpf.getisoffline(con)) {
			downFavSong(songs);
		}
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					downFavSong(songs);
					MusicSpf.setisoffline(con, true);
				} else {
					MusicSpf.setisoffline(con, false);
				}
			}
		});
		findViewById(R.id.iv_tongbu).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(con, "同步中……", 0).show();
				new CollectApi().getclodelist(con, handler);
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}


	private void listinit() {
		listView = (ListView) findViewById(R.id.lv_downsong);
		adapter = new FavSongAdapter(this, songs);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				adapter.changeColor(arg2);
				currentpos = arg2;
				Intent intent = new Intent(Constant.ACTION_PLAY);
				intent.putExtra("pos", currentpos);
				sendBroadcast(intent);
			}
		});

		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				adapter.changeColor(arg2);
				currentpos = arg2;
				new AlertDialog.Builder(con)
						.setSingleChoiceItems(
								new String[] { "下载", "分享", "删除" }, 0,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										if (which == 0) {
											dialog.dismiss();
											Song song = (Song) adapter.getItem(currentpos);
											downoneSong(song);
										} else if (which == 1) {
											dialog.dismiss();
											Song song = (Song) adapter
													.getItem(currentpos);
											Intent intent = new Intent(con,
													ShareAct.class);
											if (song.isIsnetMusic()) {
												intent.putExtra("song", song);
											}
											startActivity(intent);
										} else if (which == 2) {
											dialog.dismiss();
											Song song = adapter.getItem(currentpos);
											adapter.deletsong(currentpos);
											if (!StringUtil.isnull(song.getLocal_url())) {
												File file = new File(song.getLocal_url());
												if (file.exists()) {
													file.delete();
												}
											}
											int i = dBhelper.deletFavsong(song.getMusicid());
											if (i!=0) {
												Toast.makeText(con, song.getName()+"|删除成功", 0).show();
											}else {
												Toast.makeText(con,song.getName()+"|删除失败", 0).show();
											}
											SongApplication.getInstance().changNowPlayList(PLAYLIST.FAV_MUSIC_LIST);
										}
									}
								}).setNegativeButton("关闭", null).create()
						.show();
				return false;
			}
		});
	}

	//下载列表歌曲
	public void downFavSong(ArrayList<Song> songsList) {
		for (Song song2 : songsList) {
			downoneSong(song2);
		}
	}
	//下载一首歌曲
	public void downoneSong(Song onesong) {
		if (onesong.isIsnetMusic()) {
			Task task = new Task();
			task.name = onesong.getName();
			task.obj = onesong;
			task.type = Constant.DOWN_TYPE.MP3;
			Intent intent = new Intent(Constant.SERVICE_DOWN);
			intent.putExtra("task", task);
			sendBroadcast(intent);
		}
	}
}